function getPlatform(imageUrl) {
	return imageUrl.split('/')[2].split('.')[1];
}

function getGameId(imageUrl, platform) {
	if (platform == "steampowered") {
		return imageUrl.split('/')[6];
	} else if (platform == "desura") {
		return imageUrl.split('/')[7];
	} else {
		return 0;
	}
}

function hideAllGiveawaysForGameId(platform, id) {
	var tableCells = $("td");
	var tableCell, tdPlatform, tdId;
	for (var i = 0; i < tableCells.length; i++) {
		tableCell = tableCells.eq(i);
		var imageUrl = tableCell.css('background-image');
		if (imageUrl && imageUrl != "none") {
			tdPlatform = getPlatform(imageUrl);
			tdId = getGameId(imageUrl, tdPlatform);
			if (tdPlatform == platform && tdId == id) {
				tableCell.hide();
			}
		}
	}
}

function hideButton_clicked(event) {
	var blockedItems = $.totalStorage('blocked');
	blockedItems.push(event.data.platform + ":" + event.data.id);
	$.totalStorage('blocked', blockedItems);
	alert("This game will never be displayed anymore\n");
	hideAllGiveawaysForGameId(event.data.platform, event.data.id);
}

function addHideButton(container) {
	var imageUrl = container.css('background-image');
	if (imageUrl && imageUrl != "none") {
		var platform = getPlatform(imageUrl);
		var id = getGameId(imageUrl, platform);
		if (id != 0) {
			container.find("td.riga_2")
				.append('<input type="button" value="Hide" title="Hide all giveaways with this game">')
				.click({id: id, platform: platform},hideButton_clicked);
		}
	}
}

function galaPlus() {
	var blockedItems = $.totalStorage('blocked'); //get blocked items ids from local storage
	if (blockedItems == null || !blockedItems instanceof Array) {
		$.totalStorage('blocked', [])
	};
	var gamePlatform, appId, backgroundImageUrl, tableCell;
	// alert($.totalStorage('blocked')); //test
	var tableCells = $("td");
	for (i = 0; i < tableCells.length; i++) {
		gamePlatform = null;
		appId = null;
		backgroundImageUrl = null;
		tableCell = null;
		tableCell = tableCells.eq(i);
		backgroundImageUrl = tableCell.css('background-image');
		if (backgroundImageUrl && backgroundImageUrl != "none") {
			gamePlatform = getPlatform(backgroundImageUrl);
			appId = getGameId(backgroundImageUrl, gamePlatform);
			if (appId) {
				addHideButton(tableCell);
				if (jQuery.inArray(gamePlatform + ":" + appId, blockedItems) > -1) {
					hideAllGiveawaysForGameId(gamePlatform, appId);
				}
			}
		}
	}
}

$(function() {
	// $("body").append('<input type="button" value="Clear hidden" title="Clear hidden apps list">') // Create the element
	// .button() // Ask jQuery UI to buttonize it
	// .click(function() {
	// 	$.totalStorage('blocked', []);
	// }); // Add a click handler
	galaPlus();
});